<template>
    <view class="blood-container">
        <CmsTabs :type="2" :page-title="'造血干细胞'" @project-tab-change="handleProjectTabChange" @data-loaded="handleDataLoaded">
            <view class="footer-btn">
                <view class="primary-btn" @click="handleGoRegister">我要登记</view>
            </view>
        </CmsTabs>

        <!-- 我要登记弹窗 -->
        <view class="register-popup" v-if="showRegisterPopup" @click="handleClosePopup">
            <view class="popup-mask"></view>
            <view class="popup-content" @click.stop>
                <view class="popup-header">
                    <view class="popup-title">捐献登记</view>
                    <view class="popup-close" @click="handleClosePopup">×</view>
                </view>
                <view class="popup-form">
                    <view class="form-item">
                        <view class="form-label">姓名<text class="required">*</text></view>
                        <input class="form-input" v-model="formData.name" placeholder="请输入" />
                    </view>
                    <view class="form-item">
                        <view class="form-label">性别</view>
                        <radio-group :value="formData.gender" @change="handleGenderChange" class="radio-group">
                            <label class="radio-item">
                                <radio value="男" :checked="formData.gender === '男'" />
                                <text>男</text>
                            </label>
                            <label class="radio-item">
                                <radio value="女" :checked="formData.gender === '女'" />
                                <text>女</text>
                            </label>
                        </radio-group>
                    </view>
                    <view class="form-item">
                        <view class="form-label">手机号码<text class="required">*</text></view>
                        <input class="form-input" v-model="formData.phone" placeholder="请输入" type="number" />
                    </view>
                    <view class="form-item">
                        <view class="form-label">年龄<text class="required">*</text></view>
                        <input class="form-input" v-model="formData.age" placeholder="请输入" type="number" />
                    </view>
                    <view class="form-item">
                        <view class="form-label">意愿采集点<text class="required">*</text></view>
                        <view class="form-input-area">
                            <picker @change="handleCollectionPointChange" :value="formData.collectionPointIndex" :range="collectionPoints">
                                <view class="picker-text">{{ formData.collectionPointIndex >= 0 ? collectionPoints[formData.collectionPointIndex] : '请选择' }}</view>
                            </picker>
                            <image src="../../static/right.png" mode="widthFix" class="right-icon"></image>
                        </view>
                    </view>
                </view>
                <view class="popup-footer">
                    <view class="primary-btn" @click="handleConfirmRegister">确认登记</view>
                </view>
            </view>
        </view>

        <!-- 登记成功弹窗 -->
        <view class="success-popup" v-if="showSuccessPopup" @click="handleCloseSuccessPopup">
            <view class="popup-mask"></view>
            <view class="success-popup-content" @click.stop>
                <view class="success-icon">
                    <image src="../../static/success2.png" mode="widthFix" />
                </view>
                <view class="success-title">登记成功</view>
                <view class="success-message">感谢您的爱心奉献，后续会有红十字会工作人员与您联系。</view>
                <view class="success-btn" @click="handleCloseSuccessPopup">
                    <text class="btn-text">我知道了</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
    import { ref, onMounted } from 'vue'
    import CmsTabs from '@/components/cms-tabs/cms-tabs.vue'
    import { cellCheckIn } from '@/utils/api.js'
    import { handleFormButtonClick, handleLoginRequiredPopup } from '@/utils/loginGuard.js'

    // 弹窗控制
    const showRegisterPopup = ref(false)
    // 成功弹窗显示状态
    const showSuccessPopup = ref(false)
    
    // 表单数据
    const formData = ref({
        name: '',
        gender: '男',
        phone: '',
        age: '',
        collectionPointIndex: -1
    })
    
    // 采集点选项（五区一市）
    const collectionPoints = ['滕州市', '薛城区', '山亭区', '市中区', '峄城区', '台儿庄区']

    // 处理项目tab切换事件
    const handleProjectTabChange = (event) => {
        console.log('项目tab切换:', event)
    }

    // 处理数据加载完成事件
    const handleDataLoaded = (event) => {
        console.log('数据加载完成:', event)
    }

    // 我要登记
    const handleGoRegister = async () => {
        // 检查登录状态，如果未登录会弹出登录提示
        const canShowPopup = await handleLoginRequiredPopup('/pages/zaogan/index')
        if (canShowPopup) {
            showRegisterPopup.value = true
        }
    }
    
    // 关闭弹窗
    const handleClosePopup = () => {
        showRegisterPopup.value = false
        // 重置表单数据
        formData.value = {
            name: '',
            gender: '男',
            phone: '',
            age: '',
            collectionPointIndex: -1
        }
    }
    
    // 关闭成功弹窗
    const handleCloseSuccessPopup = () => {
        showSuccessPopup.value = false
    }
    
    // 性别选择变化
    const handleGenderChange = (e) => {
        formData.value.gender = e.detail.value
    }
    
    // 采集点选择变化
    const handleCollectionPointChange = (e) => {
        formData.value.collectionPointIndex = e.detail.value
    }
    
    // 确认登记
    const handleConfirmRegister = async () => {
        // 表单验证
        if (!validateForm()) {
            return
        }
        
        try {
            // 显示加载提示
            uni.showLoading({
                title: '提交中...'
            })
            
            // 准备提交数据
            const submitData = {
                name: formData.value.name.trim(),
                phone: formData.value.phone.trim(),
                gender: formData.value.gender,
                age: parseInt(formData.value.age),
                area: collectionPoints[formData.value.collectionPointIndex]
            }
            
            console.log('提交造血干细胞登记数据:', submitData)
            
            // 调用登记接口
            const response = await cellCheckIn(submitData)
            
            console.log('接口响应:', response)
            
            // 隐藏加载提示
            uni.hideLoading()
            
            // 检查响应结果
            if (response.code == 0) {
                // 显示成功弹窗
                showSuccessPopup.value = true
                
                // 关闭表单
                handleClosePopup()
            } else {
                // 显示错误信息
                const errorMsg = response.message || response.msg || '登记失败，请重试'
                uni.showToast({
                    title: errorMsg,
                    icon: 'none',
                    duration: 3000
                })
            }
            
        } catch (error) {
            console.error('造血干细胞登记失败:', error)
            
            // 隐藏加载提示
            uni.hideLoading()
            
            // 显示错误提示
            uni.showToast({
                title: '网络错误，请重试',
                icon: 'none',
                duration: 3000
            })
        }
    }

    // 表单验证
    const validateForm = () => {
        const { name, phone, age, collectionPointIndex } = formData.value
        
        // 必填验证
        if (!name.trim()) {
            uni.showToast({
                title: '请输入姓名',
                icon: 'none'
            })
            return false
        }
        
        if (!phone.trim()) {
            uni.showToast({
                title: '请输入手机号码',
                icon: 'none'
            })
            return false
        }
        
        if (!age.trim()) {
            uni.showToast({
                title: '请输入年龄',
                icon: 'none'
            })
            return false
        }
        
        if (collectionPointIndex < 0) {
            uni.showToast({
                title: '请选择意愿采集点',
                icon: 'none'
            })
            return false
        }
        
        // 手机号格式验证
        const phoneReg = /^1[3-9]\d{9}$/
        if (!phoneReg.test(phone)) {
            uni.showToast({
                title: '请输入正确的手机号码',
                icon: 'none'
            })
            return false
        }
        
        // 年龄验证
        const ageNum = parseInt(age)
        if (isNaN(ageNum) || ageNum < 18 || ageNum > 45) {
            uni.showToast({
                title: '年龄必须在18-45岁之间',
                icon: 'none'
            })
            return false
        }
        
        return true
    }
</script>

<style lang="scss" scoped>  
    .blood-container {
        width: 100%;
        min-height: 100vh;
        background: #f5f5f5;
        padding-bottom: 152rpx; /* 为底部按钮留出空间：100rpx(按钮高度) + 52rpx(按钮padding) */
    }

    .footer-btn {
        position: fixed;
        bottom: 0;
        left: 0;
        width: calc(100% - 48rpx);
        height: 100rpx;
        background: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 24rpx 24rpx 28rpx 24rpx;
        z-index: 100;
    }
    
    // 登记弹窗样式
    .register-popup {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 999;
        display: flex;
        align-items: flex-end;

        .popup-mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
        }

        .popup-content {
            position: relative;
            width: 100%;
            max-height: 85vh;
            min-height: 500rpx;
            background: #FFFFFF;
            border-radius: 24rpx 24rpx 0rpx 0rpx;
            z-index: 1000;
            display: flex;
            flex-direction: column;

            .popup-header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 32rpx 24rpx 24rpx 24rpx;
                position: relative;
                flex-shrink: 0;
                border-bottom: 2rpx solid #f0f0f0;

                .popup-title {
                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                    font-size: 32rpx;
                    line-height: 44rpx;
                    font-weight: 500;
                    color: #000;
                    text-align: center;
                }

                .popup-close {
                    width: 48rpx;
                    height: 48rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 40rpx;
                    color: rgba(0, 0, 0, 0.90);
                    cursor: pointer;
                    margin-left: auto;
                }
            }

            .popup-form {
                flex: 1;
                overflow-y: auto;
                padding: 0 24rpx;

                .form-item {
                    display: flex;
                    align-items: center;
                    padding: 24rpx 0;
                    border-bottom: 2rpx solid #E7E7E7;

                    &:last-child {
                        border-bottom: none;
                        padding-bottom: 32rpx;
                    }

                    &:first-child {
                        padding-top: 32rpx;
                    }

                    .form-label {
                        width: 180rpx;
                        font-size: 28rpx;
                        color: rgba(0, 0, 0, 0.60);
                        flex-shrink: 0;

                        .required {
                            color: #F9623E;
                            margin-left: 4rpx;
                        }
                    }

                    .form-input {
                        flex: 1;
                        text-align: right;
                        font-size: 28rpx;
                        border: none;
                        outline: none;
                        background: transparent;

                        &::placeholder {
                            color: rgba(0, 0, 0, 0.40);
                        }
                    }

                    .radio-group {
                        flex: 1;
                        display: flex;
                        justify-content: flex-end;
                        gap: 32rpx;

                        .radio-item {
                            display: flex;
                            align-items: center;
                            gap: 8rpx;
                            font-size: 28rpx;
                            color: rgba(0, 0, 0, 0.60);
                        }
                    }

                    .form-input-area {
                        flex: 1;
                        text-align: right;
                        display: flex;
                        align-items: center;
                        justify-content: flex-end;

                        .picker-text {
                            font-size: 28rpx;
                            color: rgba(0, 0, 0, 0.40);
                            margin-right: 8rpx;
                        }

                        .right-icon {
                            width: 24rpx;
                            height: 24rpx;
                            flex-shrink: 0;
                        }
                    }
                }
            }

            .popup-footer {
                flex-shrink: 0;
                padding: 24rpx;
                border-top: 2rpx solid #E7E8EB;
                background: #FFFFFF;

                .primary-btn {
                    width: 100%;
                    height: 88rpx;
                    background: linear-gradient(135deg, #F9623E 0%, #FF7A5A 100%);
                    border-radius: 44rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: #FFFFFF;
                    font-size: 32rpx;
                    font-weight: 500;
                    box-shadow: 0 8rpx 24rpx rgba(249, 98, 62, 0.3);
                    transition: all 0.3s ease;

                    &:active {
                        transform: scale(0.98);
                        box-shadow: 0 4rpx 12rpx rgba(249, 98, 62, 0.3);
                    }
                }
            }
        }
    }

    // 成功弹窗样式
    .success-popup {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1000;
        display: flex;
        align-items: center;
        justify-content: center;

        .popup-mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
        }

        .success-popup-content {
            position: relative;
            width: 600rpx;
            background: #FFFFFF;
            border-radius: 24rpx;
            padding: 48rpx 32rpx;
            text-align: center;
            box-shadow: 0 16rpx 48rpx rgba(0, 0, 0, 0.2);

            .success-icon {
                width: 120rpx;
                height: 120rpx;
                margin: 0 auto 32rpx;
                display: flex;
                align-items: center;
                justify-content: center;

                image {
                    width: 100%;
                    height: 100%;
                }
            }

            .success-title {
                font-size: 36rpx;
                font-weight: 600;
                color: #000000;
                margin-bottom: 24rpx;
                line-height: 1.4;
            }

            .success-message {
                font-size: 28rpx;
                color: rgba(0, 0, 0, 0.6);
                line-height: 1.6;
                margin-bottom: 48rpx;
                padding: 0 16rpx;
            }

            .success-btn {
                width: 100%;
                height: 88rpx;
                background: linear-gradient(135deg, #F9623E 0%, #FF7A5A 100%);
                border-radius: 44rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                box-shadow: 0 8rpx 24rpx rgba(249, 98, 62, 0.3);
                transition: all 0.3s ease;

                &:active {
                    transform: scale(0.98);
                    box-shadow: 0 4rpx 12rpx rgba(249, 98, 62, 0.3);
                }

                .btn-text {
                    color: #FFFFFF;
                    font-size: 32rpx;
                    font-weight: 500;
                }
            }
        }
    }
</style>